//#include "stdafx.h"
#include <windows.h>
#include "MyThread.h"
#include "process.h"

CMyThread::CMyThread(void) 
:m_hThread(NULL)
,m_nInverval(1000)
,m_pCallback(NULL)
//,m_uiThreadId(0)
{
	InitializeCriticalSection(&m_csMyBlock);
	m_hThreadEndEvent= CreateEvent(NULL, TRUE, FALSE, NULL); 
}

CMyThread::CMyThread(pfnThreadCALLBACK pCallback)
:m_hThread(NULL)
,m_nInverval(1000)
,m_pCallback(pCallback)
//,m_uiThreadId(0)
{
	InitializeCriticalSection(&m_csMyBlock);
	m_hThreadEndEvent= CreateEvent(NULL, TRUE, FALSE, NULL); 
}

CMyThread::~CMyThread(void)
{
	DeleteCriticalSection(&m_csMyBlock);
}

void CMyThread::Run()
{
}
void MyLogInfo(const char* pszClassFunc, int logType, const char* pszFormat, ...);
void CMyThread::StopThread()
{
	if (m_hThread == NULL)
		return ;
	::SetEvent(m_hThreadEndEvent);
	//OutputDebugString(_T("Before waitForSingleObject"));
	//if(m_uiThreadId)
	//{
	if(WaitForSingleObject(m_hThread,20000)==WAIT_TIMEOUT){
		TerminateThread(m_hThread,0);
		OutputDebugStringA("CMyThread::StopThread TerminateThread");
	}
	CloseHandle(m_hThread);
	m_hThread = NULL;
	//}
	//while (WaitForSingleObject(m_hThreadEndEvent, 0) == WAIT_OBJECT_0)
		//Sleep(2);
	//OutputDebugString(_T("After waitForSingleObject"));
	//if(WaitForSingleObject(m_hThreadEndEvent, 0) != WAIT_OBJECT_0)
	//	CloseHandle(m_hThread);
	//m_hThread = NULL;
	//m_uiThreadId = 0;
}
void CMyThread::StartThread(int nInterval)
{
	m_nInverval = nInterval;
	if (m_hThread == NULL)
	{
		HANDLE hThread;
		UINT uiThreadId = 0;
		hThread = (HANDLE)CreateThread(NULL,  // Security attributes
			4*1024*1024,    // stack
			(LPTHREAD_START_ROUTINE)ThreadProc,   // Thread proc
			this,   // Thread param
			CREATE_SUSPENDED,   // creation mode
			NULL);   // Thread ID

		if ( NULL != hThread)
		{
			//m_uiThreadId = uiThreadId;
			//SetThreadPriority(hThread, THREAD_PRIORITY_ABOVE_NORMAL);
			ResumeThread( hThread );
			m_hThread = hThread;
			return ;
		}
	}
}

void CMyThread::RunThread()
{
	CoInitialize(NULL);
	while(true)
	{
		if (WaitForSingleObject(m_hThreadEndEvent, m_nInverval) == WAIT_OBJECT_0)
		{
			OutputDebugString("WaitForSingleObject break!\n");
			break;
		}
		if (m_pCallback == NULL)
			Run();
		else
			m_pCallback(NULL);
	}
	::ResetEvent(m_hThreadEndEvent);
	CoUninitialize();
}

UINT WINAPI CMyThread::ThreadProc(LPVOID pParam)
{
	CMyThread *pThread = (CMyThread *)pParam;
	pThread->RunThread();
	return 0;
}